/*
 * @Descripttion: 
 * @Author: junhuafly
 * @Date: 2020-02-28 09:43:45
 * @LastEditors: junhuafly
 * @Email: junhuafly@163.com
 * @LastEditTime: 2020-04-20 09:52:01
 */
// pages/note/detail.js
import {
  noteAPI
} from "./../../../api/note.js"

import {
  userAPI
} from "./../../../api/user.js"
import {
  goodsAPI
} from './../../../api/goods.js'
import {
  returnStatus,
  returnStatusToast
} from '../../../utils/util'
import {
  utils
} from './../../../components/lib/utils'
import Toast from '../../../@vant/weapp/dist/toast/toast';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    showNav: true,
    isFixed: false,
    noteId: 287,
    images: [],
    likeList: [],
    details: {},
    operation: {},
    createDate: '',
    isCollect: false,
    showReply: false,
    isFollow: false,
    isLike: false,
    relates: [], //推荐
    reply: [],
    goods: [], //带货
    totalReply: 0,
    replyVal: '',
    subReply: {}
  },
  onHideReplyMask() {
    this.setData({
      showReply: false
    })
  },
  // 举报
  async onBlock(){
    wx.navigateTo({
      url: '/pages/feedback/index?noteId='+this.data.noteId,
    })
    
  },
  onShowReplyMask({
    detail
  }) {
    this.setData({
      showReply: true,
      subReply: detail
    })
  },
  toInfo(){
    wx.navigateTo({
      url: '/pages/mine/home/index?customerId='+this.data.details.authorId
    });
  },
  toLike(){
    const {noteId} = this.data
    wx.navigateTo({
      url: `/pages/mine/attention/index?noteId=${noteId}`,
    })
  },
  toReply({
    currentTarget
  }) {
    const {
      detail
    } = currentTarget.dataset
    wx.navigateTo({
      url: './../../reply/index',
      success: function (res) {
        // 通过eventChannel向被打开页面传送数据
        res.eventChannel.emit('commentCardInfo', {
          detail
        })
      }
    })
  },
  // 操作笔记收藏及喜欢
  async onNote({
    target
  }) {
    const {
      id
    } = target
    const isCollect = id === 'collect'
    const _this = this
    const noteStatus = isCollect ? !this.data.isCollect : !this.data.isLike
    const _ = await noteAPI.handleNoteLikeOrCollect({
      noteId: this.data.noteId,
      type: noteStatus ? "YES" : "NO",
      handle: isCollect ? 1 : 2
    })
    if (_.code === 200) {
      _this.setData(isCollect ? {
        isCollect: noteStatus,
        'operation.collect': noteStatus ? ++_this.data.operation['collect'] : --_this.data.operation['collect']
      } : {
        isLike: noteStatus,
        'operation.like': noteStatus ? ++_this.data.operation['like'] : --_this.data.operation['like']

      })
      Toast({
        message: "操作成功",
        duration: 800
      });
    }
  },

  // 操作关注取消关注
  async handleCustomerFollow() {
    const _ = await userAPI.handleFollowUser({
      follow: !this.data.isFollow,
      followCustomerId: this.data.details.authorId
    })
    returnStatusToast(_, () => {
      this.setData({
        isFollow: !this.data.isFollow
      })
    })
  },

  // 操作收藏商品
  async handleCollectGoods({
    target
  }) {
    const {
      productid,
      collect,
      index
    } = target.dataset
    const type = collect ? "NO" : "YES"
    const curGoods = `goods[${index}].collect`

    goodsAPI.handleCollect({
      productId: productid,
      type: collect ? "NO" : "YES"
    }).then(async _ => {
      await returnStatus(_)
      const isCollect = type !== "NO"
      Toast({
        message: `${isCollect?'收藏':'取消收藏'}成功`,
        duration: 800,
      })
      this.setData({
        [curGoods]: isCollect
      })
    })
  },

  // 评论成功
  replySuccess() {
    const _this = this
    Toast({
      message: '评论成功！',
      duration: 800,
      onClose() {
        _this.setData({
          showReply: false
        })
        // 重新加载评论
        _this.loadReply()
      }
    })
  },

  loadOtherInfo(noteId){
    noteAPI.queryRelate({
      authorId: this.data.details.authorId
    }).then(async _ => {
      const relates = await returnStatus(_)
      this.setData({
        relates
      })
    })
    // 笔记次数
    noteAPI.operateNote({
      noteId
    })
    this.loadReply()
    if(!wx.getStorageSync('token')) return
    // 检测是否被收藏
    noteAPI.checkCollect({
      noteId
    }).then(async _ => {
      await returnStatus(_)
      const isCollect = _.data
      this.setData({
        isCollect
      })
    })
    // 查看是否关注
    userAPI.hasFollowed({
      followCustomerId: this.data.details.authorId
    }).then(async _ => {
      const isFollow = await returnStatus(_)
      this.setData({
        isFollow: isFollow !== "NOT_FOLLOWED"
      })
    })
    noteAPI.checkLike({
      noteId
    }).then(async _ => {
      await returnStatus(_)
      const isLike = _.data
      this.setData({
        isLike
      })
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var appInst =  getApp();
    appInst.setTitle('笔记详情')
    const {noteId,id} = options
    this.setData({noteId:noteId||id})
    // 加载数据
    noteAPI.queryNoteDetailInit({
      noteId: this.data.noteId
    }).then(async _ => {
      const res = await returnStatus(_)
      const {
        images,
        likeList,
        details,
        operation
      } = res
      this.setData({
        images,
        likeList: likeList.records,
        details,
        operation,
        createDate: utils.relativeTime(details.createDate)
      })
      this.loadOtherInfo(noteId)
    })
    // 获取带货信息
    noteAPI.queryNoteGoods({
      noteId: this.data.noteId
    }).then(async _ => {
      const goods = await returnStatus(_)
      this.setData({
        goods
      })
    })

  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  },
  // 加载评论
  loadReply() {
    noteAPI.queryReply({
      noteId: this.data.noteId,
      pageNum: 1,
      pageSize: 10
    }).then(async _ => {
      const {
        records
      } = await returnStatus(_)
      this.setData({
        reply: records,
        totalReply: _.data.total
      })
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  onTaggerNav: function ({
    detail
  }) {
    this.setData({
      isFixed: detail.isFixed
    })
  }
})